﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Text;
using EzDesk.Core.Model;
using EzDesk.Utility.Extensions;
using EzDesk.Utility.Web.Extensions;

namespace EzDesk.Utility.Web.Controllers
{
    public class JsonExResult : JsonResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                response.Write(Data.ToJson());
            }
        }
    }

    public class EzDeskController : Controller
    {

        protected Guid CurrentUserId
        {
            get
            {
                return new Guid(HttpContext.User.Identity.Name);
            }
        }

        protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            JsonResult result = base.Json(data, contentType, contentEncoding, behavior);
            JsonExResult resultEx = new JsonExResult()
            {
                ContentEncoding = result.ContentEncoding,
                ContentType = result.ContentType,
                Data = result.Data,
                JsonRequestBehavior = result.JsonRequestBehavior
            };
            return resultEx;
        }

        protected string getEpochForJavascript(DateTime dateTime)
        {
            return string.Format("'{0}'", dateTime.ToEpoch());
        }

        protected virtual ActionResult ReturnView(string r, string txtInfo, object routeValues)
        {
            SetReturnInfoText(txtInfo);
            return View(routeValues);
        }

        protected ActionResult ReturnView(string actionName, string controllerName, string txtInfo, object routeValues)
        {
            SetReturnInfoText(txtInfo);
            return RedirectToAction(actionName, controllerName, routeValues);
        }

        protected void SetReturnInfoText(string txtInfo)
        {
            TempData["txtInfo"] = txtInfo;
        }

        private void putSessionToRouteValues(AppSession currentSession,ref RouteValueDictionary routeValues)
        {
            if (routeValues == null)
            {
                routeValues = new RouteValueDictionary();
            }
            routeValues["ez_user"] = currentSession.UserId;
        }


    }

}
